package com.lucas.rpc.framework.server.register;

import com.lucas.rpc.framework.entity.URL;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: LiuCheng
 * @description: 一个假的远程注册中心（用于模拟）
 * @date: 2023-12-04 15:02
 **/
public class FakeRemoteRegister {

    private static Map<String, List<URL>> map = new HashMap();


    public static void register(String interfaceName, URL url) throws Exception {
        List<URL> urlList = map.getOrDefault(interfaceName,new ArrayList<>());
        urlList.add(url);
        map.put(interfaceName,urlList);

        //创建一个文件，用于client和server共享这个map，否则两个进程无法共享map，就会导致client无法发现服务
        File file = new File("/share.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);
        oos.writeObject(map);
        oos.close();
    }

    public static List<URL> getURLs(String interfaceName) throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/share.txt"));
        map = (Map<String,List<URL>>)ois.readObject();
        ois.close();
        return map.get(interfaceName);
    }

}
